<template>
	<div class="about">
		<el-page-header @back="goBack"/>
		<el-form @submit.native.prevent="save" label-position="top">
			
		<el-row style=" display: flex;justify-content:flex-start;align-items:center">
		<h1 style="font-size: 20px;">{{id ? '编辑':'提交'}}成果</h1>
		<el-form-item>
				<el-button style="margin-left:1rem"
					size="small" :loading="uploading" type="primary"
					native-type="submit">保存</el-button>
			</el-form-item>
			
		</el-row>
			<el-col :span="12">
				
			<el-form-item label="获奖者作品或项目名称">
				<el-input v-model="model.name"></el-input>
			</el-form-item>
				
			
					<el-form-item label="所属赛事">
						<el-select filterable v-model="model.contest" placeholder="请选择" style="width: 100%;">
							<el-option
								v-for="item in contests" :key="item" :label="item.name" :value="item.name">
							</el-option>
						</el-select>
					</el-form-item>
			<el-row type="flex">
					<el-form-item label="参赛时间">
						<el-date-picker v-model="model.match_date" type="date" placeholder="选择日期">
						</el-date-picker>
					</el-form-item>
					<el-form-item label="证书获奖日期">
						<el-date-picker v-model="model.award_date" type="date" placeholder="选择日期">
						</el-date-picker>
					</el-form-item>
			</el-row>


			<el-form-item label="参赛学生数">
				<el-input-number :min="1" v-model="length" @change="handleChange"></el-input-number>
			</el-form-item>


			<el-carousel trigger="click" :autoplay="false" style="margin-top:0.5rem">
				<el-carousel-item v-for="student in model.students" :key="student"  style="width:30rem;margin-left:4.5rem;">
				<el-card>
				<el-form-item label="获奖学生学号">
					<el-input placeholder="请输入" v-model="student.id"></el-input>
				</el-form-item>
				<el-form-item label="获奖者学生姓名">
					<el-input placeholder="请输入" v-model="student.name"></el-input>
				</el-form-item>
				</el-card>
			</el-carousel-item>
			</el-carousel>

			<el-form-item label="指导教师">
				<el-input placeholder="多个名字中间用逗号隔开" v-model="model.teachers"></el-input>
			</el-form-item>
			<el-form-item label="授奖单位名称">
				<el-input v-model="model.organizer"></el-input>
			</el-form-item>

			<el-form-item label="介绍内容">
				<editor v-model="model.intro"></editor>
			</el-form-item>
			
		</el-col>

		<el-col :span="12">
			<el-form-item label="文档上传（可预览）">
				<el-upload class="upload-demo"
					:http-request = this.$qiniu :action="qiniuUrl"
					:headers="getAuthHeaders()"
					:on-preview="handleFilePreview" :before-upload="beforeFileUpload"
					:on-remove="handleFilesRemove" :before-remove="beforeRemove" multiple
					:file-list="model.files">
					<el-button :loading="uploading"
					size="small" type="primary">点击上传</el-button>
					<div slot="tip" class="el-upload__tip">上传文档大小不能超过25MB，用于展示（大于25MB的PPT建议转换成PDF文件并压缩大小）</div>
				</el-upload>
			</el-form-item>

			<el-divider/>

			<el-form-item ref="uploader" label="相关文件上传（不可预览）">
				<el-upload class="upload-demo" :action="qiniuUrl"
					:http-request = this.$qiniu
					:headers="getAuthHeaders()" :before-upload="beforeUpload"
					:on-remove="handleCompressdFilesRemove" :before-remove="beforeRemove" multiple
					:file-list="model.compressed_files">
					<el-button :loading="uploading"
					size="small" type="primary">点击上传</el-button>
					<div slot="tip" class="el-upload__tip">将相关文件打包成压缩包(zip或rar格式)后上传</div>
				</el-upload>
			</el-form-item>

			<el-divider/>

			<el-form-item label="演示视频(仅限mp4)">
				<el-upload class="upload-demo" :action="qiniuUrl"
					:http-request = this.$qiniu
					:headers="getAuthHeaders()"
					:on-preview="handlePreview"
					:on-remove="handleVideosRemove" :before-remove="beforeRemove" multiple
					:before-upload="beforeVideoUpload" :file-list="model.videos">
					<el-button :loading="uploading"
					size="small" type="primary">点击上传</el-button>
			</el-upload>
			</el-form-item>

			<el-divider/>
			
			<el-form-item label="成果展示封面（没有则会展示默认图片）">
				<cover-uploader></cover-uploader>
			</el-form-item>

			<el-form-item label="证书图片">
				<certificate-uploader>
				</certificate-uploader>
			</el-form-item>
			<el-drawer :visible.sync="drawer"
				title="预览"
				direction="rtl"
				size="50%">
				<video-player v-if="playerOptions['sources'][0]['src'] !=''"
						class="video-player vjs-custom-skin"
						ref="videoPlayer"
						:playsinline="true"
						:options="playerOptions"
				></video-player>
				<iframe v-else-if="fileUrl!=''" :src="fileUrl"  width="100%" height="100%" border="0"></iframe>
			</el-drawer>

			<transition name="el-fade-in-linear">
			<el-card v-if="uploading" class="isFixed" shadow="hover">
			<div title="文件正在上传中，请不要刷新页面">
				文件正在上传中，请不要刷新页面
				<el-progress :text-inside="true" :stroke-width="26"
				:percentage="percentage"></el-progress>
			</div>
			</el-card>
			</transition>

			<el-form-item label="审核" v-if="$store.state.user.role=='super_admin'">
				<el-radio-group size="small" v-model="model.check">
					<el-radio-button label="通过"></el-radio-button>
					<el-radio-button label="不通过"></el-radio-button>
				</el-radio-group>
			</el-form-item>
		</el-col>
		</el-form>
	</div>
	
</template>

<script>
	// require styles
	import 'video.js/dist/video-js.css'
	import 'vue-video-player/src/custom-theme.css'
	import {videoPlayer} from 'vue-video-player'
	import Editor from '../components/Editor'
	import coverUploader from '../components/CoverUploader'
	import certificateUploader from '../components/CertificateUploader'
	export default {
		components: {
			videoPlayer,
			editor:Editor,
			coverUploader,
			certificateUploader,
		},
		props: {
			id: {}
		},
		data() {
			return {
				model: {
					match_date: '',
					award_date: '',
					students: [{
						id: '',
						name: ''
					}],
					files: [{
						name: '',
						url: '',
					}],
					check:'',
					contest:'',
					teachers:'',
					intro:'',
				},
				contests:[],
				length: 1,
				drawer: false,
				introView:false,
				playerOptions: {
					// videojs options
					muted: true,
					language: 'zh-CN',
					aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
					playbackRates: [0.75, 1.0, 1.25, 1.5, 2.0],
					sources: [{
						type: "video/mp4",
						src: ''
					}],
					poster: "/static/images/author.jpg",
					notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
					controlBar: {
						timeDivider: true, // 当前时间和持续时间的分隔符
						durationDisplay: true, // 显示持续时间
				},
				editor_id:'',
				//这是根据你七牛云创建空间时所选择的地区
				qiniuUrl : 'https://upload-z2.qiniup.com',
				uploading: false,
				uploadingFile:'',
				percentage:0,
				fileUrl: '',
				headerText:'',
				
				}
			}
		},
		methods: {
			goBack() {
				this.$router.go(-1)
			},

			// 验证文件合法性
			beforeUpload (file) {
			const isZip = file.type === 'application/x-zip-compressed' || file.type === 'application/octet-stream'
			if (!isZip) {
				this.$message.error('上传文件只能是zip或rar格式!')
			}
			return isZip
			},

			beforeVideoUpload(file) {
				var FileExt = file.name.replace(/.+\./, "");
				if (['mp4'].indexOf(FileExt.toLowerCase()) === -1) {
					this.$message({
						type: 'warning',
						message: '请上传后缀名为mp4的视频！'
					});
					return false;
				}
			},
			
			beforeFileUpload(file) {
				const isLt25M = file.size / 1024 / 1024 < 25;
				if (!isLt25M) {
					this.$message.error('上传文档大小不能超过 25MB!');
				}
				return isLt25M;
			},

			async save() {
				this.uploading = true
				let res
				if (this.model.name == null || this.model.name.length == 0) {
					this.$message({
						type: 'warning',
						message: '内容不能为空'
					})
				} else {
					if (this.id) {
						// 编辑
						res = await this.$http.put(`rest/achievement/${this.id}`, this.model)
						if(res){
							this.$message({
								type: 'success',
								message: '保存成功'
							})
							this.uploading = false
						}
					} else {
						//新建
						this.model.editor_id = this.$store.state.user.id
						this.model.check = '未审核'
						res = await this.$http.post('rest/achievement', this.model)
						this.form = {
							picture: ""
						};
						console.log(res.data)
						this.$router.push('/achievement/list')
						this.$message({
							type: 'success',
							message: '上传成功'
						})
					}
				}
			},
			async pass() {
				this.model.check = "通过审核"
				await this.$http.put(`rest/achievement/${this.id}`, this.model)
				this.$router.push('/achievement/list')
				this.$message({
					type: 'success',
					message: '审核通过！'
				})
			},
			async fail() {
				this.model.check = "审核未通过"
				await this.$http.put(`rest/achievement/${this.id}`, this.model)
				this.$router.push('/achievement/list')
				this.$message({
					type: 'warning',
					message: '审核不通过！'
				})
			},
			async fetch() {
				const res = await this.$http.get(`rest/achievement/${this.id}`)
				this.editor_id = this.$store.state.user.id
				console.log(this.editor_id)
				if(res){
					this.model = res.data
					this.length = res.data.students.length
					this.$store.commit('setCover',this.model.cover)
					this.$store.commit('setCertificate',this.model.certificate_picture)
				}
			},
			async fetchContests() {
				const res = await this.$http.get(`rest/contests`)
				if(res)
					this.contests = res.data
			},
			
			handleChange() {
				while (this.length > this.model.students.length)
					this.model.students.push({})
				while (this.length < this.model.students.length)
					this.model.students.pop()
			},

			handlePreview(file) {
				this.drawer = true
				this.playerOptions['sources'][0]['src'] =file.url; //动态更改流地址 
				console.log(file.url)
			},

			handleFilePreview(file) {
				this.drawer = true
				this.fileUrl = 'http://view.officeapps.live.com/op/view.aspx?src='+file.url
				console.log(file.url)
			},

			handleVideosRemove(file, fileList) {
				for (var i = 0; i < fileList.length; i++) {
					if (fileList[i] == file){
						fileList.splice(i,1)
					}
				}
				this.model.videos = fileList
			},

			handleFilesRemove(file, fileList) {
				for (var i = 0; i < fileList.length; i++) {
					if (fileList[i] == file){
						fileList.splice(i,1)
					}
				}
				this.model.files = fileList
			},

			handleCompressdFilesRemove(file, fileList) {
				for (var i = 0; i < fileList.length; i++) {
					if (fileList[i] == file){
						fileList.splice(i,1)
					}
				}
				this.model.compressed_files = fileList
			},

			beforeRemove(file) {
				return this.$confirm(`确定移除 ${ file.name }？`);
			},
			handleFileListChange(file, fileList) {
				this.fileList = fileList.slice(-3);
			},

			handleScroll () {
				let scrollTop = window.pageYOffset || document.documentElement.scrollTop || 
				document.body.scrollTop
				console.log(scrollTop)
			},
			toggle (tabIndex) {
				this.whichTab = tabIndex
				window.location.href = '#searchBar' // 锚点
			}
		},
		mounted(){
			window.addEventListener('scroll', this.handleScroll)
		},
		created() {
			this.id && this.fetch()
			this.fetchContests()
		},
		computed: {
			//这里需要把store动态的数据放到computed里面才会同步更新视图
			getFiles(){
				console.log(this.$store.state.files)
                return this.$store.state.files
            },
			getUploading(){
				console.log(this.$store.state.uploading)
                return this.$store.state.uploading
            },
			getArticleContent(){
                return this.$store.state.article_content
            }
		},
		watch:{
			getFiles(newFile){
				switch(newFile.file_type){
					case 'file':
						this.model.files.push({"name":newFile.name, "url":newFile.url,})
						break
					case 'video':
						this.model.videos.push({"name":newFile.name, "url":newFile.url,})
						break
					case 'compressed_file':
						this.model.compressed_files.push({"name":newFile.name, "url":newFile.url,})
						break
					case 'cover':
						this.model.cover = newFile.url
						break
					case 'certificate':
						this.model.certificate_picture = newFile.url
						break
				}
				this.uploading=this.$store.state.uploading
				console.log("!"+newFile)
			},
			getUploading(newInfo){
				this.uploading = newInfo.status
				this.percentage = newInfo.percentage
				console.log(this.uploading)
				console.log(this.percentage)
				this.$forceUpdate()
			},
			getArticleContent(newInfo){
				this.model.intro = newInfo
				console.log(newInfo)
				this.$forceUpdate()
			},
		}
	}
</script>
<style>
	.el-form {
		margin: auto;
	}

	.el-form-item {
		width: 57%;
	}
	
  .isFixed{
    position:fixed;
    background-color:#fff;
    top:6rem;
	right: 6rem;
    z-index:999;
  }
</style>